from functools import wraps
from flask import request, jsonify, current_app

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 延迟导入以避免循环依赖
        from app.src.auth.services import AuthService
        
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({
                'code': 401,
                'message': '未提供认证token'
            }), 401

        auth_service = AuthService()
        result = auth_service.verify_token(token)

        if not result.get('valid'):
            return jsonify({
                'code': 401,
                'message': result.get('message', 'token无效或已过期')
            }), 401

        return f(*args, **kwargs)
    return decorated_function